package com.wltjack.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller层异常统一处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response defaultErrorHandler(HttpServletRequest req, Exception e){
        log.error("defaultErrorHandler >>> {}", e.getMessage());
        e.printStackTrace();
        // 这里可以根据不同的异常引起的类做不同的处理
        String exceptionName = ClassUtils.getShortName(e.getClass());
        log.info("defaultErrorHandler > exceptionName = {}", exceptionName);
        log.info("defaultErrorHandler > requestUrl = {}", req.getRequestURL());
        Response response = new Response(10000, e.getMessage(), null);
        return response;
    }


    @ExceptionHandler(value = ArithmeticException.class)
    @ResponseBody
    public Response arithmeticExceptionHandler(HttpServletRequest req, Exception e){
        log.error("arithmeticExceptionHandler >>> {}", e.getMessage());
        e.printStackTrace();
        String exceptionName = ClassUtils.getShortName(e.getClass());
        log.info("arithmeticExceptionHandler > exceptionName = {}", exceptionName);
        log.info("arithmeticExceptionHandler > requestUrl = {}", req.getRequestURL());
        Response response = new Response(10000, e.getMessage(), null);
        return response;
    }
}
